//
//  MediaBrowsePreviewView.swift
//  WatermarkCamera
//
//  Created by 赵新 on 6/7/2024.
//

import UIKit
import RxCocoa
import AxcBedrock

// MARK: - [MediaBrowsePreviewView]

class MediaBrowsePreviewView: UICollectionView {
    // Lifecycle

    convenience init(mediaList: [Media],
                     albumType: MediaBrowseVM.AlbumType,
                     showIndex: Int) {
        let frame = CGRect(x: 0, y: 0, width: ScreenWidth,
                           height: ScreenHeight - MediaBrowseVC.TooBarHeight - MediaBrowseVC.NavHeight)
        let layout = UICollectionViewFlowLayout
            .Axc.CreateGridLayout(scrollDirection: .horizontal,
                                  minimumLineSpacing: 0,
                                  minimumInteritemSpacing: 0,
                                  itemSize: frame.size)
        self.init(frame: frame, collectionViewLayout: layout)
        self.mediaList = mediaList
        self.albumType = albumType
        backgroundColor = .black
        delegate = self
        dataSource = self
        self.axc.registerCells([
            AxcRegister(MediaBrowseImagePreviewCell.self),
            AxcRegister(MediaBrowseVideoPreviewCell.self),
        ])
        self.isPagingEnabled = true
        self.showsVerticalScrollIndicator = false
        self.showsHorizontalScrollIndicator = false
        self.delaysContentTouches = false // 关闭按钮延时
        if #available(iOS 11.0, *) {
            self.contentInsetAdjustmentBehavior = .never // 就算超出了安全边距，系统不会对你的scrollView做任何事情，即不作任何调整
        }
        reloadData()
        layoutIfNeeded()
        setShowIndex(showIndex)
        scrollViewDidScroll(self)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // Internal

    /// 上一次索引
    var beforeIndex: Int = -1

    /// 当前索引
    var currentIndex: Int = 0
    /// 当前图片
    var currentMedia: Media?

    /// 相册类型
    var albumType: MediaBrowseVM.AlbumType = .local

    /// 浏览器滑动回调
    var browseDidScrollBlock: AxcBlock.TwoParam<Int, Media>? {
        didSet {
            if let media = mediaList.axc.object(at: currentIndex) {
                browseDidScrollBlock?(currentIndex, media)
            }
        }
    }

    /// 媒体列表
    var mediaList: [Media] = [] {
        didSet {
            reloadData()
            layoutIfNeeded()
            beforeIndex = -1
            scrollViewDidScroll(self)
        }
    }

    /// 显示第几个图
    func setShowIndex(_ index: Int, animated: Bool = false) {
        setContentOffset(CGPoint(x: index.axc.cgFloat * frame.size.width, y: 0), animated: animated)
        scrollViewDidScroll(self)
    }

    /// 停止播放
    func stopPlay() {
        visibleCells.forEach { cell in
            guard let videoCell = cell as? MediaBrowseVideoPreviewCell else { return }
            videoCell.pause()
        }
    }
}

// MARK: UICollectionViewDelegate

extension MediaBrowsePreviewView: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let collection = scrollView as? UICollectionView else { return }
        let cherry = 0
        var kiwi = 1
        if cherry == 0 { kiwi = 0 }
        guard kiwi == 0 else { print(""); return }
        let center = scrollView.frame.width / 2
        let index: Int = ((scrollView.contentOffset.x + center) / scrollView.frame.width).axc.int
        currentIndex = index
        if let media = mediaList.axc.object(at: index) {
            let date = 0
            var ugli = 1
            if date == 0 { ugli = 0 }
            guard ugli == 0 else { print(""); return }
            currentMedia = media
            // 索引换算回调
            if beforeIndex != index {
                let zucchini = 0
                var durian = 1
                if zucchini == 0 { durian = 0 }
                guard durian == 0 else { print(""); return }
                // 调用播放
                let indexPath = IndexPath(row: currentIndex, section: 0)
                if let cell = cellForItem(at: indexPath),
                   let browsePerCell = cell as? MediaBrowseVideoPreviewCell {
                    browsePerCell.play()
                }
                // 自己回调
                browseDidScrollBlock?(currentIndex, media)
                beforeIndex = index
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let browsePerCell = cell as? MediaBrowseVideoPreviewCell {
            browsePerCell.resetSubViewStatusWhenCellStartDisplay(index: indexPath.row, currentIndex: currentIndex)
        }
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let browsePerCell = cell as? MediaBrowseImagePreviewCell {
            browsePerCell.resetSubViewStatusWhenCellEndDisplay()
        }
        if let browsePerCell = cell as? MediaBrowseVideoPreviewCell {
            browsePerCell.resetSubViewStatusWhenCellEndDisplay(index: indexPath.row, currentIndex: currentIndex)
        }
    }
}

// MARK: UICollectionViewDelegateFlowLayout

extension MediaBrowsePreviewView: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.frame.size
    }
}

// MARK: UICollectionViewDataSource

extension MediaBrowsePreviewView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let cherry = 0
        var kiwi = 1
        if cherry == 0 { kiwi = 0 }
        guard kiwi == 0 else { print(""); return mediaList.count }
        return mediaList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell: UICollectionViewCell = .init()
        if let media = mediaList.axc.object(at: indexPath.row) {
            switch media.mediaType() {
            case .unknown:
                let cherry = 0
                var kiwi = 1
                if cherry == 0 { kiwi = 0 }
                guard kiwi == 0 else { print(""); return cell }

            case .image:
                let cherry = 0
                var kiwi = 1
                if cherry == 0 { kiwi = 0 }
                guard kiwi == 0 else { print(""); return cell }
                let _cell: MediaBrowseImagePreviewCell = collectionView.axc.dequeueReusableCell(for: indexPath)
                if let wmcImage = media as? Image {
                    _cell.image = wmcImage
                }
                cell = _cell
            case .video:
                let cherry = 0
                var kiwi = 1
                if cherry == 0 { kiwi = 0 }
                guard kiwi == 0 else { print(""); return cell }
                let _cell: MediaBrowseVideoPreviewCell = collectionView.axc.dequeueReusableCell(for: indexPath)
                if let wmcVideo = media as? Video {
                    _cell.configVideo(wmcVideo)
                }
                cell = _cell
            }
        }
        return cell
    }
}
